package com.example.chinesechess.presentation.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.chinesechess.domain.ai.ChessAI
import com.example.chinesechess.domain.ai.EasyAI
import com.example.chinesechess.domain.ai.MediumAI
import com.example.chinesechess.domain.ai.HardAI
import com.example.chinesechess.domain.model.ChessBoard
import com.example.chinesechess.domain.model.ChessPiece
import com.example.chinesechess.domain.model.Move
import com.example.chinesechess.domain.model.Position
import com.example.chinesechess.domain.model.Side
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class GameViewModel @Inject constructor() : ViewModel() {

    // Game state
    private val _gameState = MutableStateFlow<GameState>(GameState.Initial)
    val gameState: StateFlow<GameState> = _gameState.asStateFlow()

    // UI state
    private val _uiState = MutableStateFlow(GameUiState())
    val uiState: StateFlow<GameUiState> = _uiState.asStateFlow()

    // Board representation
    private val board = ChessBoard()

    // Selected position
    private var selectedPosition: Position? = null
    
    // AI related properties
    private var isAiMode = false
    private var aiSide = Side.BLACK  // AI默认执黑
    private var aiPlayer: ChessAI? = null
    private var aiThinkingTime = 500L // AI思考时间（毫秒）

    init {
        startNewGame()
    }

    /**
     * 开始新游戏
     * @param gameMode 游戏模式: "local", "ai_easy", "ai_medium", "ai_hard"
     */
    fun startNewGame(gameMode: String = "local") {
        viewModelScope.launch {
            // Initialize board and state
            val pieces = board.getAllPieces()
            _uiState.update { 
                it.copy(
                    pieces = pieces,
                    currentSide = Side.RED,
                    selectedPosition = null,
                    validMoves = emptyList(),
                    lastMove = null,
                    isInCheck = false,
                    isCheckmate = false
                )
            }
            _gameState.value = GameState.Playing
            
            // 设置AI模式
            setupAiMode(gameMode)
        }
    }
    
    /**
     * 设置AI模式和难度
     */
    private fun setupAiMode(gameMode: String) {
        isAiMode = gameMode.startsWith("ai_")
        
        if (isAiMode) {
            aiSide = Side.BLACK
            aiPlayer = when (gameMode) {
                "ai_easy" -> EasyAI()
                "ai_medium" -> MediumAI()
                "ai_hard" -> HardAI()
                else -> EasyAI() // 默认使用简单AI
            }
        } else {
            // 本地对战模式
            aiPlayer = null
        }
    }

    /**
     * 处理棋盘上的位置选择
     */
    fun onSquareSelected(position: Position) {
        viewModelScope.launch {
            // 如果游戏已结束或当前是AI回合，则忽略用户输入
            val currentState = _gameState.value
            if (currentState is GameState.GameOver) return@launch
            if (isAiMode && board.currentSide == aiSide) return@launch
            
            handleSquareSelection(position)
        }
    }

    /**
     * 处理位置选择逻辑
     */
    private fun handleSquareSelection(position: Position) {
        val piece = board.getPiece(position)
        
        // 如果已经有选中的棋子
        if (selectedPosition != null) {
            // 尝试移动选中的棋子到此位置
            val move = Move(selectedPosition!!, position)
            
            if (board.isValidMove(move) && !board.wouldBeInCheck(move, board.currentSide)) {
                makeMove(move)
            } else {
                // 如果新选择的是己方棋子，则选中该棋子
                if (piece != null && piece.side == board.currentSide) {
                    selectPiece(position)
                } else {
                    // 无效移动，清除选择
                    clearSelection()
                }
            }
        } else {
            // 尚未选择棋子
            if (piece != null && piece.side == board.currentSide) {
                selectPiece(position)
            }
        }
    }
    
    /**
     * 选择一个位置上的棋子
     */
    private fun selectPiece(position: Position) {
        selectedPosition = position
        val validMoves = board.getValidMoves(position)
        
        _uiState.update {
            it.copy(
                selectedPosition = position,
                validMoves = validMoves
            )
        }
    }
    
    /**
     * 清除当前选择
     */
    private fun clearSelection() {
        selectedPosition = null
        _uiState.update {
            it.copy(
                selectedPosition = null,
                validMoves = emptyList()
            )
        }
    }
    
    /**
     * 在棋盘上走一步棋
     */
    private fun makeMove(move: Move) {
        val success = board.makeMove(move)
        
        if (success) {
            val isInCheck = board.isInCheck(board.currentSide)
            val isCheckmate = board.isCheckmate()
            
            _uiState.update {
                it.copy(
                    pieces = board.getAllPieces(),
                    currentSide = board.currentSide,
                    selectedPosition = null,
                    validMoves = emptyList(),
                    lastMove = move,
                    isInCheck = isInCheck,
                    isCheckmate = isCheckmate
                )
            }
            
            if (isCheckmate) {
                _gameState.value = GameState.GameOver(board.currentSide.opposite())
            } else if (isAiMode && board.currentSide == aiSide) {
                // 如果是AI回合，让AI走棋
                makeAiMove()
            }
        }
        
        clearSelection()
    }
    
    /**
     * AI走棋逻辑
     */
    private fun makeAiMove() {
        viewModelScope.launch {
            // 添加短暂延迟，模拟AI思考
            delay(aiThinkingTime)
            
            // 计算并执行AI最佳移动
            aiPlayer?.calculateMove(board)?.let { aiMove ->
                makeMove(aiMove)
            } ?: run {
                // AI无法找到有效移动，认输
                _gameState.value = GameState.GameOver(aiSide.opposite())
            }
        }
    }
    
    /**
     * 悔棋
     * 在对战AI模式中，需要撤销两步（用户和AI的回合）
     */
    fun undoMove() {
        viewModelScope.launch {
            if (board.undoLastMove()) {
                // 在AI模式下，如果回到了AI回合，再撤销一步
                if (isAiMode && board.currentSide == aiSide) {
                    board.undoLastMove()
                }
                
                _uiState.update {
                    it.copy(
                        pieces = board.getAllPieces(),
                        currentSide = board.currentSide,
                        selectedPosition = null,
                        validMoves = emptyList(),
                        lastMove = board.getLastMove(),
                        isInCheck = board.isInCheck(board.currentSide),
                        isCheckmate = false
                    )
                }
                
                if (_gameState.value is GameState.GameOver) {
                    _gameState.value = GameState.Playing
                }
            }
        }
    }
    
    /**
     * 认输
     */
    fun resign() {
        viewModelScope.launch {
            _gameState.value = GameState.GameOver(board.currentSide.opposite())
        }
    }
}

/**
 * 游戏状态表示
 */
sealed class GameState {
    object Initial : GameState()
    object Playing : GameState()
    data class GameOver(val winner: Side?) : GameState()
}

/**
 * 游戏UI状态
 */
data class GameUiState(
    val pieces: List<ChessPiece> = emptyList(),
    val currentSide: Side = Side.RED,
    val selectedPosition: Position? = null,
    val validMoves: List<Position> = emptyList(),
    val lastMove: Move? = null,
    val isInCheck: Boolean = false,
    val isCheckmate: Boolean = false
) 